package utils

import (
	"encoding/json"
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"io/ioutil"
	"appengine"
    "appengine/urlfetch"
    "strings"
    "regexp"
)


func FromJson(jsonString string, gc *GithubCollection) error {
	data := &gc.Pool
	b := []byte(jsonString)
	
	return json.Unmarshal(b, data)
}

func GetCurl(url string, r *http.Request) string {
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	resp, err := client.Get(url)
	
	if err != nil {
		return ""
	}
	
	defer resp.Body.Close()
    contents, err := ioutil.ReadAll(resp.Body)
	if (err != nil) {
		return ""
	}
	
	return string(contents); 
}

func GetReadmeContent(r *http.Request, readme *Readme) {
	var doc *goquery.Document
  	var e error

	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	
	resp, err := client.Get(readme.Url)
	
	if  err != nil {
		panic(err.Error())
	}

	if doc, e = goquery.NewDocumentFromResponse(resp); e != nil {
		panic(e.Error())
	}
	var contents string
	if (doc.Find("#readme").Has(".plain").Length() > 0) {
		contents = doc.Find("#readme .plain").Text()
	} else if (doc.Find("#readme").Has(".entry-content").Length() > 0) {
		contents = doc.Find("#readme .entry-content").Text()
	}
	 
	readme.Content = contents
}

func StringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}

func GetStringSpecial(str string) string {
	re := regexp.MustCompile(`[=]{3}([^=]+)+[=]{3}`)
	rs := re.FindString(str)
	return strings.TrimSpace(strings.Replace(rs, "=", "", -1))
}

func GetStringUpperLongest(str string) string {

	re := regexp.MustCompile(`([A-Z0-9]{1}[a-zA-Z]+[ ]{0,1})+`)	
	rs := re.FindAllString(str, -1)
	strLongest := ""
	strCount := 0
	for i:=0; i< len(rs); i++ {
		spl := strings.Split(strings.TrimSpace(rs[i]), " ")
		if len(spl) > strCount {
			strCount = len(spl)
			strLongest = strings.TrimSpace(rs[i])
		}
	}
	
	return strLongest
}

func GetAlias(str string) string {
	return strings.ToLower(strings.Replace(strings.TrimSpace(str), " ", "-", -1))
}

func CheckUrl(str string) bool {
	re := regexp.MustCompile(`^((http://)|(https://)){1}[a-zA-Z0-9-]+([.]{1}[a-zA-Z0-9-]+)+([/]+[^/]*)*`)
	
	if (re.MatchString(str)) {
		return true
	} else {
		return false
	}
}